package com.huicoo.forestmanager.ui.main;

import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.base.BaseActivity;
import com.huicoo.forestmanager.base.BaseApplication;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.ui.home.HomeFragment;
import com.huicoo.forestmanager.ui.home.HomeMenuFragment;
import com.huicoo.forestmanager.ui.me.MeFragment;
import com.huicoo.forestmanager.ui.patrol.PatrolFragmentVersion2;
import com.huicoo.forestmanager.ui.statistics.StatisticsFragment;
import com.huicoo.forestmanager.ui.web.CustomWebFragment;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.update.AppUpdateDownInfo;
import com.huicoo.forestmanager.widget.update.DownManager;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends BaseActivity implements Handler.Callback {
    @BindView(R.id.iv_home)
    ImageView iv_home;
    @BindView(R.id.iv_patrol)
    ImageView iv_patrol;
    @BindView(R.id.iv_statistics)
    ImageView iv_statistics;
    @BindView(R.id.iv_me)
    ImageView iv_me;
    @BindView(R.id.line_home)
    View line_home;
    @BindView(R.id.line_patrol)
    View line_patrol;
    @BindView(R.id.line_statistics)
    View line_statistics;
    @BindView(R.id.line_me)
    View line_me;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer_layout;

    private List<Fragment> fragmentList;
    private int lastFragmentIndex = -1;
    private HomeMenuFragment homeMenuFragment;

    private WeakHandler handler;
    private boolean isQuit;
    private boolean isFirstGPSChecked; //打开APP后是否首次检查过GPS

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        handler = new WeakHandler(this);

        initFragments();

        initDrawerLayout();

        switchPage(0);

        //检查软件更新
        checkUpdateVersion();
    }

    @OnClick(R.id.rl_home)
    public void clickHome() {
        switchPage(0);
    }

    @OnClick(R.id.rl_patrol)
    public void clickPatrol() {
        switchPage(1);
    }

    @OnClick(R.id.rl_statistics)
    public void clickStatistics() {
        switchPage(2);
    }

    @OnClick(R.id.rl_me)
    public void clickMe() {
        switchPage(3);
    }

    // 初始化fragment
    private void initFragments() {
        fragmentList = new ArrayList<>();
        String baseUrl = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.BASE_URL);
        if (TextUtils.isEmpty(baseUrl)) {
            baseUrl = "http://47.110.80.118:8003/";
        }
        fragmentList.add(HomeFragment.getInstance(CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/index.html")));
        fragmentList.add(PatrolFragmentVersion2.getInstance());
        // 统计页面根据user level区分。 1是村级用户，（其他镇级以上用户）
        String statisticsPage = "patrolandStatistics.html";
        if (TextUtils.equals(CustomUtils.getUserLevel(), "1")) {
            statisticsPage = "patroland.html";
        }
        fragmentList.add(StatisticsFragment.getInstance(CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/" + statisticsPage)));
        fragmentList.add(MeFragment.getInstance(CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/huliny.html")));

        LogUtils.v("gogogo main url home = " + CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/index.html"));
        LogUtils.v("gogogo main url statistics = " + CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/" + statisticsPage));
        LogUtils.v("gogogo main url me = " + CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/huliny.html"));
    }

    //设置左侧菜单页面内容
    private void initDrawerLayout() {
        String baseUrl = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.BASE_URL);
        if (TextUtils.isEmpty(baseUrl)) {
            baseUrl = "http://47.110.80.118:8003/";
        }
        String drawerLayoutUrl = CustomUtils.urlAddParams(getApplicationContext(), baseUrl + "h5/menu.html");
        LogUtils.v("gogogo menu url = " + drawerLayoutUrl);
        setDrawerLayout(drawerLayoutUrl);
        HomeFragment homeFragment = (HomeFragment) fragmentList.get(0);
        homeFragment.setOnCustomWebListener(new CustomWebFragment.OnCustomWebListener() {
            @Override
            public void openMenu() {
                drawer_layout.openDrawer(Gravity.START);
            }
        });
    }

    // 切换页面
    private void switchPage(int currentIndex) {
        if (lastFragmentIndex != currentIndex) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (lastFragmentIndex != -1) {
                transaction.hide(fragmentList.get(lastFragmentIndex));
            }
            if (!fragmentList.get(currentIndex).isAdded()) {
                transaction.add(R.id.mainContainer, fragmentList.get(currentIndex));
            }
            transaction.show(fragmentList.get(currentIndex)).commitNowAllowingStateLoss();

            lastFragmentIndex = currentIndex;
            switchNavigation();
        }
    }

    // 切换导航栏状态
    private void switchNavigation() {
        iv_home.setImageResource(lastFragmentIndex == 0 ? R.drawable.icon_shouye_hot : R.drawable.icon_shouye);
        line_home.setVisibility(lastFragmentIndex == 0 ? View.VISIBLE : View.GONE);

        iv_patrol.setImageResource(lastFragmentIndex == 1 ? R.drawable.icon_xuncha_hot : R.drawable.icon_xuncha);
        line_patrol.setVisibility(lastFragmentIndex == 1 ? View.VISIBLE : View.GONE);

        iv_statistics.setImageResource(lastFragmentIndex == 2 ? R.drawable.icon_tongji_hot : R.drawable.icon_tongji);
        line_statistics.setVisibility(lastFragmentIndex == 2 ? View.VISIBLE : View.GONE);

        iv_me.setImageResource(lastFragmentIndex == 3 ? R.drawable.icon_wode_hot : R.drawable.icon_wode);
        line_me.setVisibility(lastFragmentIndex == 3 ? View.VISIBLE : View.GONE);
    }

    //设置左侧菜单页面内容
    private void setDrawerLayout(String drawerLayoutUrl) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        homeMenuFragment = HomeMenuFragment.getInstance(CustomUtils.urlAddParams(getApplicationContext(), drawerLayoutUrl));
        transaction.add(R.id.menuContainer, homeMenuFragment);
        transaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (drawer_layout.isDrawerOpen(Gravity.START)) {
                drawer_layout.closeDrawer(Gravity.START);
                return false;
            }

            if (!isQuit) {
                isQuit = true;
                ToastUtils.show("再按一次返回键退出程序");
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isQuit = false;
                    }
                }, 2000);
            } else {
                finish();
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //检查是否开启位置信息
        checkOpenGPS();
        //清除缓存
        BaseApplication.clearWebCache();
    }

    //检查是否开启GPS
    private void checkOpenGPS() {
        long lastTime = SharedPreferenceUtil.LoadLongData(Constants.PROJECT_NAME, Constants.WEB_CACHE_TIME);
        long nowTime = System.currentTimeMillis();
        if (!isFirstGPSChecked || nowTime - lastTime >= 30 * 60 * 1000) {
            isFirstGPSChecked = true;
            LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                ToastUtils.show("系统检测到未开启GPS定位服务");
                Intent intent = new Intent();
                intent.setAction(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            CustomWebFragment fragment = null;
            //requestCode 211和311是Home 212和312是Me 213和313是HomeMenu 214和314是Statistics
            switch (requestCode) {
                case 211:
                case 311:
                    fragment = (CustomWebFragment) fragmentList.get(0);
                    break;
                case 212:
                case 312:
                    fragment = (CustomWebFragment) fragmentList.get(1);
                    break;
                case 213:
                case 313:
                    fragment = homeMenuFragment;
                    break;
                case 214:
                case 314:
                    fragment = (CustomWebFragment) fragmentList.get(2);
                    break;
                default:
                    break;
            }
            if (fragment != null) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //软件更新相关
    private static final int REQUEST_EXTERNAL_STORAGE = 101;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private DownManager downManager;

    private void toUpdateVersion(AppUpdateDownInfo info) {
        if (downManager == null) {
            downManager = new DownManager(this);
            String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ForestManager/apk/";
            File root = new File(rootPath);
            if (!root.exists()) {
                root.mkdirs();
            }
            String downloadPath = rootPath + "ForestManager_" + info.version + ".apk";
            downManager.setDownInfo(info, downloadPath, false);
            downManager.setOnPermissionListener(new DownManager.OnPermissionListener() {
                @Override
                public void noPermission() {
                    ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                }
            });
        }
        downManager.showAppUpdateDialog();
    }

    private AppUpdateDownInfo dealDownInfo(String version, String downloadUrl, String description) {
        AppUpdateDownInfo info = new AppUpdateDownInfo();
        info.version = version;
        info.downloadUrl = downloadUrl;
        info.description = description;
        return info;
    }

    private void checkUpdateVersion() {
        String url = "http://47.110.80.118/CommSvc/GetValue.aspx?type=checksoftupdated&key=ForestManager_sj_" + CustomUtils.getBaseUrlKey() + "&format=json&version=" + CustomUtils.getAppVersionName(this);
        LogUtils.v("gogogo get new version url = " + url);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Message msg = new Message();
                msg.what = 200;
                msg.obj = response.body();
                handler.sendMessage(msg);
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }

        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 200:
                try {
                    if (msg.obj != null) {
                        ResponseBody body = (ResponseBody) msg.obj;
                        String json = body.string();
                        LogUtils.v("gogogo get new version result = " + json);
                        if (!TextUtils.isEmpty(json)) {
                            JSONObject jsonObject = new JSONObject(json);
                            int State = jsonObject.optInt("State", 0);
                            if (State == 1) {
                                String Version = jsonObject.optString("Version", "");
                                LogUtils.v("gogogo Version = " + Version);
                                if (!TextUtils.isEmpty(Version)) {
                                    //版本号尾数为偶数，弹出更新对话框
                                    String lastCode = Version.substring(Version.length() - 1);
                                    Pattern p = Pattern.compile("^\\d*[02468]$");
                                    Matcher m = p.matcher(lastCode);
                                    if (m.matches()) {
                                        String Desc = jsonObject.optString("Desc", "");
                                        if (!TextUtils.isEmpty(Version)) {
                                            String DownloadUrl = "http://47.110.80.118/CommSvc/GetValue.aspx?type=getnewestsoft&key=forestmanager_sj_" + CustomUtils.getBaseUrlKey() + "&version=" + Version;
                                            toUpdateVersion(dealDownInfo(Version, DownloadUrl, Desc));
                                        }
                                    }
                                }

                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
        return false;
    }
}
